package com.sync.hkmjsyncdata.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sync.hkmjsyncdata.pojo.po.AuthInfo;
import com.sync.hkmjsyncdata.pojo.po.HkEventRecord;
import com.sync.hkmjsyncdata.pojo.po.HkEventVehicle;
import com.sync.hkmjsyncdata.service.IAuthInfoService;
import com.sync.hkmjsyncdata.service.IHkEventRecordService;
import com.sync.hkmjsyncdata.service.IHkEventVehicleService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class SendMjEventVehicle {

    @Value("${gyhlw.host}")
    private String requestHost;

    @Resource
    IAuthInfoService authInfoService;

    @Resource
    IHkEventVehicleService hkEventVehicleService;


    /**
     * 发送门禁打开记录
     */
    @XxlJob("SendMjEventVehicle")
    public void SendMjEventVehicleData() {
        XxlJobHelper.log("开始上传海康人员打卡记录");
        AuthInfo authInfo = authInfoService.getById("1111");
        if (ObjectUtils.isEmpty(authInfo)) {
            XxlJobHelper.log("获取认证信息失败，取消删上传海康车辆进场记录");
            return;
        }
        //上传新增数据
        sendData(authInfo.getToken());
    }

    private void sendData(String token) {
        LambdaQueryWrapper<HkEventVehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(HkEventVehicle::getOpTyp)
                .orderByAsc(HkEventVehicle::getEntranceDate)
                .last("limit 999");
        List<HkEventVehicle> addResult = hkEventVehicleService.list(queryWrapper);
        XxlJobHelper.log("开始推送数据,{}条", addResult.size());
        if (ObjectUtils.isEmpty(addResult)) {
            return;
        }
        JSONObject params = new JSONObject();
        params.put("dataList", addResult);
        MediaType mediaType = MediaType.parse("application/json");
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        RequestBody body = RequestBody.create(mediaType, params.toJSONString());
        Request request = new Request.Builder()
                .url(requestHost + "/api/event/carEventList")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", token)
                .build();
        try {
            Response response = client.newCall(request).execute();
            assert response.body() != null;
            String responseData = response.body().string();
            XxlJobHelper.log("推送结果:{}", responseData);
            if (ObjectUtils.isNotEmpty(responseData)) {
                JSONObject result = JSON.parseObject(responseData);
                if(result.getInteger("status")==200){
                    addResult.forEach(event->event.setOpTyp(4));
                    hkEventVehicleService.updateBatchById(addResult);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
